package com.bungarus.bridge;

import com.bungarus.bridge.config.BusiBridgeServerChildHandlerInitializer;
import com.bungarus.cluster.ClusterManager;
import com.bungarus.cluster.NodeInfo;
import com.bungarus.model.AbstractBungarusServer;
import com.bungarus.model.AbstractBungarusServerWithMultipleClients;
import io.netty.channel.ChannelHandler;
import org.apache.log4j.Logger;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * Created by tang on 2018/12/30.
 */
public class BusiBridge extends AbstractBungarusServerWithMultipleClients {
    Logger logger = Logger.getLogger(BusiBridge.class);
    public static final String TAG = "busi-bridge";

    /**
     * communication port with nodes in busi cluster
     */
    private static final int PORT_6060 = 6060;
    /**
     * the cluster to which busi-bridge node as client will connect
     * the busi-bridge cluster will transfer the message to the busi node
     * which has high performance to process large group
     */
    private static final String[] CLUSTER_TAGS = {CLUSTER_TAG_BUSI};

    public static void main(String[] args) throws Exception {
        int[] messagePorts = {PORT_6060};

        BusiBridge busi = new BusiBridge();
        busi.bind(System.getProperty(AbstractBungarusServer.HOST), messagePorts, null); // use messagePorts for heartbeat checking directly
        busi.initClusterAndConnectRemoteNode();
        busi.initRemedy();
        busi.listen(null);
    }

    /*
     * The BusiBridge node as client only connects to Busi node has capability to process large group.
     */
    @Override
    public CopyOnWriteArrayList<NodeInfo> calcRemoteServerNodes(CopyOnWriteArrayList<NodeInfo> originList) {
        List<NodeInfo> queue = originList.stream().filter(NodeInfo::isHighPerformance).collect(Collectors.toList());
        CopyOnWriteArrayList<NodeInfo> result =  new CopyOnWriteArrayList<>(queue);
        queue.clear();
        return result;
    }

    @Override
    public ChannelHandler getChildHandlerInitializer() {
        return new BusiBridgeServerChildHandlerInitializer(this);
    }

    @Override
    public String[] getRemoteNodeTags() {
        return CLUSTER_TAGS;
    }

    @Override
    public String getTag() {
        return TAG;
    }

    @Override
    public String tagPortString4Connection() {
        return "(busi|6060)";
    }

}
